#!/usr/bin/env python
# encoding: utf-8

import sys
import tornado.web
import tornado.ioloop
import tornado.httpserver
import json
import config
import logging

from lib.utils import ConfigSectionMap
from lib.JobQ import JobQueue
from lib.app_mysql import appMysql as db

reload(sys)
sys.setdefaultencoding("utf-8")

log = logging.getLogger("")


class MainHandler(tornado.web.RequestHandler):
    def init_config(self):
        self.config = ConfigSectionMap("GLOBAL")

    def auth(self, tgt):
        return True


class show(MainHandler):
    def get(self):
        return self.write(json.dumps(config.config))


class Alert(MainHandler):
    def post(self):
        self.init_config()
        if self.auth(tgt=False):
            title = self.get_argument("title")
            content = self.get_argument("content")
            target = self.get_argument("target")

            try:
                alertQueue = JobQueue(self.config.get("alert_queue"))
                alertQueue.connection()
                alertQueue.put(dict(title=title, content=content, target=target))
            except Exception as e:
                return self.write(json.dumps({"code": -1, "data": "raise unKonwError."}))

            return self.write(json.dumps({"code": 0, "data":"The data upload success."}))
        else:
            return self.write(json.dumps({"code": -1, "data": "permission deny....."}))


class AddRule(MainHandler):
    def post(self, *args, **kwargs):
        if self.auth(tgt=False):
            rule = self.get_argument("rule")
            action = self.get_argument("action")
            match_field = self.get_argument("match_field")

            if self.on_save_db(rule, action, match_field):
                return self.write(json.dumps({"code": 0, "data": "add config success."}))
            else:
                return self.write(json.dumps({"code": -1, "data": "add conifg error"}))

    def on_save_db(self, rule, action, match_field):
        sql = "insert into config(rule, action, match_field) values('%s', '%s', '%s');" %(rule, action, match_field)
        log.info(sql)
        db.autocommit(True)
        cursor = db.cursor()
        try:
            cursor.execute(sql)
            return True
        except Exception as e:
            log.error("Save config error...reason: {e}".format(e=e))
            return False
        finally:
            cursor.close()


class SyncResult(MainHandler):
    def post(self, *args, **kwargs):
        if self.auth(tgt=False):
            return self.write("ok")


class TornadoServer:
    app = tornado.web.Application([(r'/status', show),
                                   (r'/api/alert/push', Alert),
                                   (r'/api/config/add', AddRule),
                                   ])

    def __init__(self):
        pass

    @classmethod
    def run(cls):
        tor_server = tornado.httpserver.HTTPServer(cls.app)
        tor_server.listen(8000, address='0.0.0.0')
        tornado.ioloop.IOLoop.instance().start()
